/*
 * GccApplication10.c
 *
 * Created: 3/16/2015 8:40:45 AM
 *  Author: Clinton
 */ 


#define F_CPU 8000000UL //XTAL = 8 MHz
#include <avr/io.h>
#include <util/delay.h>
#include "avr/interrupt.h"
int main ()
{ 

	DDRB = 0x12;								//PB1 & PB4 as output
	DDRC = 0xFF;								//set C as an output port
	PORTD = 0x10;								//set Port D pin 4 as input
	
	TCCR1A = 0x40;								//clears OCR1A on compare match
	TCCR1B = 0x0C;								//Phase Correct PWM, inverted, N = 64
	OCR1A = 0x85EE;
	
	TCCR0A = 0x00;								//timer 0 is set to normal mode
	TCCR0B = 0x07;								//set timer 0 to accept an external clock and count on rising edge
	TCNT0 = 0x00;								//clear counter								
	
	OCR0A = 4;									//set compare value
	TIMSK0 = (1<<OCIE0A);
	sei ();										//enable interrupts
	
	while (1) 
	{
		do 
		{
			if(TCNT0 == 20)						//set threshold
			{
				TCNT0 = 0;						//clear counter
				PORTB = (0<<PB4);				//clear portb
			}
		PORTC = TCNT0;							//update portc with counter value
		} while ((TIFR0&(0x01<<TOV0))==0);		
		TIFR0 = 0x01<<TOV0;						//clear overflow flag
	}
	return 0;
}

ISR (TIMER0_COMPA_vect)
{
	PORTB = PORTB ^ (1<<PB4);					//toggle pinb 4
	OCR0A += 5;									//update new compare value
	if(OCR0A >= 20)
		OCR0A = 4;								//reset compare value if counter goes above threshold	
}